package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
@ResponseBody
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private HttpSession session;

    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        ResultInfo loginInfo = employeeService.login(username, password);
        Employee employee = (Employee) loginInfo.getData();
        session.setAttribute("SESSION_EMPLOYEE", employee);
        return loginInfo;
    }

    @PostMapping("/employee/logout")
    public ResultInfo logout() {
        session.invalidate();

        return ResultInfo.success(null);
    }

    @GetMapping("/employee/find")
    public ResultInfo find(String name) {
        List<Employee> employeeList = employeeService.findByName(name);
        return ResultInfo.success(employeeList);
    }

    @PostMapping("/employee")
    public ResultInfo saveEmployee(@RequestBody Employee employee) {
        System.out.println(employee);
        employeeService.saveEmployee(employee);
        return ResultInfo.success(null);
    }

    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id) {
        Employee employee = employeeService.findById(id);
        return ResultInfo.success(employee);
    }
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee) {
        employeeService.update(employee);
        return ResultInfo.success(null);
    }

}
